package com.zhiyou.app.shop.manager.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.zhiyou.app.shop.manager.dao.IShoppingTrolleyDao;
import com.zhiyou.app.shop.manager.dao.pojo.ShoppingTrolley;

@Repository
public class ShoppingTrolleyDaoImpl extends BaseHibernateDAO<ShoppingTrolley, String> implements IShoppingTrolleyDao {
	
	
	public ShoppingTrolleyDaoImpl() {
		super(ShoppingTrolley.class);
	}

	public List<ShoppingTrolley> findByCriteria(ShoppingTrolley t) {
		Criteria cri = getSession().createCriteria(t.getClass().getName());
		if(null != t.getUserDetail())
			cri.add(Restrictions.eq("userDetail.id", t.getUserDetail().getId()));
		if(null != t.getGoods())
			cri.add(Restrictions.eq("goods.id", t.getGoods().getId()));
		return cri.list();
	}

	public List<ShoppingTrolley> findTrolleyDetailByUserId(String userId) {
		Criteria cri = getSession().createCriteria(ShoppingTrolley.class.getName());
		cri.createAlias("goods", "g");
		cri.add(Restrictions.eq("g.isDelete", Boolean.FALSE));
		cri.add(Restrictions.eq("userDetail.id", userId));
		List<ShoppingTrolley> list = cri.list();;
		return list;
	}

	public void deleteByOrderId(String orderId, String userId) {
		
		String sql = "delete from shopping_trolley  where user_id=:userId and goods_id " +
						"in(" +
						"	select od.goods_id from order_detail od where od.order_id=:orderId" +
						")";
		SQLQuery sqlQuery = this.getSession().createSQLQuery(sql);
		
		sqlQuery.setParameter("userId", userId);
		
		sqlQuery.setParameter("orderId", orderId);
		
		sqlQuery.executeUpdate();
	}

}
